#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Create by zhang
# Create on 2022/6/22 10:36
import json
from os import path, sep
from typing import List

from config.config import config
from domain.report.common.period_enum import PeriodEnum
from domain.report.dto.balance_sheet_dto import BalanceSheetDTO
from domain.report.spider.xbrl_sse.balance_sheet_spider import balance_sheet_spider
from domain.report.spider.xbrl_sse.assembler.balance_sheet_assembler import xbrl2dtos


prefix_path = path.join(config.get("data", "folder"), "report")


def insert(dto:BalanceSheetDTO) -> bool:
    if not dto or contain(dto):
        return False
    basic_path = f"{prefix_path}{sep}{dto.stock_code}{sep}balance_sheet_{dto.period}.json"
    with open(basic_path, "a", encoding="utf-8") as file:
        file.write(json.dumps(dto.__dict__))
        return True


def insert_batch(dto_list:List[BalanceSheetDTO]) -> bool:
    if not dto_list or len(dto_list) == 0:
        return False
    for dto in dto_list:
        if not contain(dto):
            insert(dto)
    return True


def get(stock_code:str, year:int, period:PeriodEnum, is_consolidate:bool=False) -> BalanceSheetDTO:
    basic_path = f"{prefix_path}{sep}{stock_code}{sep}balance_sheet_{period}.json"
    with open(basic_path, "r", encoding="utf-8") as file:
        line = file.readline()
        if line:
            balance_sheet_dict = json.loads(line)
            if balance_sheet_dict["year"] == year and balance_sheet_dict["is_consolidate"] == is_consolidate:
                balance_sheet = BalanceSheetDTO()
                balance_sheet.__dict__ = balance_sheet_dict
                return balance_sheet
    balanceSheet_dict = balance_sheet_spider(stock_code, year, period)
    dto_list = xbrl2dtos(balanceSheet_dict, stock_code, period)
    insert_batch(dto_list)
    for dto in dto_list:
        if dto.year == year:
            return dto
    return None


def contain(dto:BalanceSheetDTO) -> bool:
    if not dto:
        return False
    basic_path = f"{prefix_path}{sep}{dto.stock_code}{sep}balance_sheet_{dto.period}.json"
    with open(basic_path, "r", encoding="utf-8") as file:
        line = file.readline()
        if line:
            balance_sheet_dict = json.loads(line)
            if dto.stock_code == balance_sheet_dict["stock_code"] and dto.period == balance_sheet_dict["period"]:
                return True
    return False